const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const livesElement = document.getElementById('lives');
const gameOverElement = document.getElementById('game-over');
const finalScoreElement = document.getElementById('final-score');
const restartBtn = document.getElementById('restart-btn');
const fullscreenBtn = document.getElementById('fullscreen-btn');

function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight - 50; // 减去header的高度
}

window.addEventListener('resize', resizeCanvas);
resizeCanvas();

let score = 0;
let lives = 3;
let fruits = [];
let isCutting = false;
let lastCutPosition = { x: 0, y: 0 };
let cutLines = []; // 用于存储切割线

const emojis = {
    apple: '😊',
    banana: '😃',
    orange: '😎',
    bomb: '💣'
};

class Fruit {
    constructor(x, y, type) {
        this.x = x;
        this.y = y;
        this.type = type;
        this.radius = 30;
        this.speed = 2;
        this.angle = Math.random() * Math.PI * 2;
    }

    draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = this.type === 'bomb' ? '#000' : this.type === 'apple' ? '#f00' : this.type === 'banana' ? '#ff0' : '#f90';
        ctx.fill();
        ctx.closePath();

        // 绘制表情符号
        ctx.font = `${this.radius * 1.5}px Arial`; // 字体大小与水果半径成比例
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillStyle = '#fff'; // 表情符号颜色
        ctx.fillText(emojis[this.type], this.x, this.y);
    }

    update() {
        this.y += this.speed;
        if (this.y > canvas.height + this.radius) {
            this.y = -this.radius;
            this.x = Math.random() * canvas.width;
        }
    }
}
function createFruit() {
    const fruits = [
        { type: 'apple', weight: 5 },
        { type: 'banana', weight: 5 },
        { type: 'orange', weight: 5 },
        { type: 'bomb', weight: 1 } // 炸弹的权重较低
    ];
 
    // 根据权重随机选择水果类型
    const totalWeight = fruits.reduce((sum, fruit) => sum + fruit.weight, 0);
    let random = Math.random() * totalWeight;
    let selectedFruit;
 
    for (const fruit of fruits) {
        if (random < fruit.weight) {
            selectedFruit = fruit.type;
            break;
        }
        random -= fruit.weight;
    }
 
    const x = Math.random() * canvas.width;
    const y = -50;
    fruitsArray.push(new Fruit(x, y, selectedFruit));
}


function spawnFruit() {
    const types = ['apple', 'banana', 'orange', 'bomb'];
    const type = types[Math.floor(Math.random() * types.length)];
    if (type !== 'bomb' || Math.random() < 0.8) { // 80% chance of not being a bomb
        fruits.push(new Fruit(Math.random() * canvas.width, -50, type));
    }
}

function drawBlade(x, y) {
    cutLines.push({ x1: lastCutPosition.x, y1: lastCutPosition.y, x2: x, y2: y });
    if (cutLines.length > 10) { // 保留最多10条切割线
        cutLines.shift();
    }
}

function drawCutLines() {
    cutLines.forEach(line => {
        const gradient = ctx.createLinearGradient(line.x1, line.y1, line.x2, line.y2);
        gradient.addColorStop(0, '#00f'); // 起始颜色为蓝色
        gradient.addColorStop(0.5, '#0ff'); // 中间颜色为青色
        gradient.addColorStop(1, '#00f'); // 结束颜色为蓝色

        ctx.beginPath();
        ctx.moveTo(line.x1, line.y1);
        ctx.lineTo(line.x2, line.y2);
        ctx.strokeStyle = gradient;
        ctx.lineWidth = 5;
        ctx.stroke();
        ctx.closePath();
    });
}

function checkCollision(x, y) {
    for (let i = fruits.length - 1; i >= 0; i--) {
        const fruit = fruits[i];
        const dx = x - fruit.x;
        const dy = y - fruit.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance < fruit.radius) {
            if (fruit.type !== 'bomb') {
                score += 10;
                scoreElement.textContent = `分数: ${score}`;
            } else {
                lives--;
                livesElement.textContent = `生命: ${lives}`;
                if (lives <= 0) {
                    gameOver();
                }
            }
            fruits.splice(i, 1);
            return true;
        }
    }
    return false;
}

function gameOver() {
    gameOverElement.classList.remove('hidden');
    finalScoreElement.textContent = `最终分数: ${score}`;
}

function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    fruits.forEach(fruit => fruit.update());
    fruits.forEach(fruit => fruit.draw());
    drawCutLines(); // 绘制切割线
    requestAnimationFrame(gameLoop);
}

function toggleFullscreen() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen().catch(err => {
            console.error(`全屏错误: ${err.message}`);
        });
    } else {
        document.exitFullscreen();
    }
}

canvas.addEventListener('mousedown', (e) => {
    isCutting = true;
    lastCutPosition = { x: e.clientX - canvas.offsetLeft, y: e.clientY - canvas.offsetTop };
});

canvas.addEventListener('mousemove', (e) => {
    if (isCutting) {
        const x = e.clientX - canvas.offsetLeft;
        const y = e.clientY - canvas.offsetTop;
        drawBlade(x, y);
        checkCollision(x, y);
        lastCutPosition = { x, y };
    }
});

canvas.addEventListener('mouseup', () => {
    isCutting = false;
});

fullscreenBtn.addEventListener('click', toggleFullscreen);

restartBtn.addEventListener('click', () => {
    score = 0;
    lives = 3;
    fruits = [];
    cutLines = []; // 重置切割线
    scoreElement.textContent = `分数: ${score}`;
    livesElement.textContent = `生命: ${lives}`;
    gameOverElement.classList.add('hidden');
    gameLoop();
});

setInterval(spawnFruit, 1000);
gameLoop();